<template>
  <div class="finance-audit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="header-title">财务审核管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="batchAudit" :disabled="!selectedVouchers.length">
              <el-icon><Check /></el-icon>
              批量审核
            </el-button>
            <el-button @click="exportAuditLog">
              <el-icon><Download /></el-icon>
              导出审核日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 审核状态统计 -->
      <div class="audit-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card pending">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.pending }}</div>
                <div class="stat-label">待审核</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card approved">
              <div class="stat-icon">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.approved }}</div>
                <div class="stat-label">已审核</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card rejected">
              <div class="stat-icon">
                <el-icon><Close /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.rejected }}</div>
                <div class="stat-label">已驳回</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card posted">
              <div class="stat-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.posted }}</div>
                <div class="stat-label">已过账</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索过滤器 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="凭证号">
            <el-input v-model="searchForm.voucherNo" placeholder="请输入凭证号" clearable />
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable>
              <el-option label="待审核" value="pending" />
              <el-option label="已审核" value="approved" />
              <el-option label="已驳回" value="rejected" />
              <el-option label="已过账" value="posted" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核人">
            <el-input v-model="searchForm.auditor" placeholder="请输入审核人" clearable />
          </el-form-item>
          <el-form-item label="审核日期">
            <el-date-picker
              v-model="searchForm.auditDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchAuditRecords">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 审核记录列表 -->
      <el-table 
        :data="auditRecords" 
        stripe 
        border 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="voucherNo" label="凭证号" width="150" />
        <el-table-column prop="voucherType" label="凭证类型" width="120">
          <template #default="scope">
            <el-tag :type="getVoucherTypeTagType(scope.row.voucherType)">
              {{ getVoucherTypeText(scope.row.voucherType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderId" label="关联订单" width="150" />
        <el-table-column prop="totalAmount" label="金额" width="120" align="right">
          <template #default="scope">
            ¥{{ scope.row.totalAmount?.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="scope">
            <el-tag :type="getAuditStatusTagType(scope.row.auditStatus)">
              {{ getAuditStatusText(scope.row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditor" label="审核人" width="100" />
        <el-table-column prop="auditTime" label="审核时间" width="160" />
        <el-table-column prop="auditRemark" label="审核意见" min-width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="viewVoucherDetail(scope.row)"
              v-if="scope.row.auditStatus === 'pending'"
            >
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="approveVoucher(scope.row)"
              v-if="scope.row.auditStatus === 'pending'"
            >
              <el-icon><Check /></el-icon>
              审核
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="rejectVoucher(scope.row)"
              v-if="scope.row.auditStatus === 'pending'"
            >
              <el-icon><Close /></el-icon>
              驳回
            </el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="postVoucher(scope.row)"
              v-if="scope.row.auditStatus === 'approved'"
            >
              <el-icon><Document /></el-icon>
              过账
            </el-button>
            <el-button 
              size="small" 
              @click="viewAuditHistory(scope.row)"
            >
              <el-icon><Clock /></el-icon>
              历史
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核弹窗 -->
    <el-dialog 
      v-model="auditDialog.visible" 
      :title="auditDialog.title"
      width="50%"
      @close="closeAuditDialog"
    >
      <el-form :model="auditDialog.form" :rules="auditRules" ref="auditFormRef" label-width="100px">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditDialog.form.auditResult">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核意见" prop="auditRemark">
          <el-input 
            v-model="auditDialog.form.auditRemark" 
            type="textarea" 
            :rows="4"
            :placeholder="auditDialog.form.auditResult === 'approved' ? '请输入审核通过意见' : '请输入驳回原因'"
          />
        </el-form-item>

        <el-form-item label="审核级别" prop="auditLevel">
          <el-select v-model="auditDialog.form.auditLevel" placeholder="请选择审核级别">
            <el-option label="一级审核" value="level1" />
            <el-option label="二级审核" value="level2" />
            <el-option label="三级审核" value="level3" />
          </el-select>
        </el-form-item>

        <el-form-item label="紧急程度" prop="urgency">
          <el-select v-model="auditDialog.form.urgency" placeholder="请选择紧急程度">
            <el-option label="普通" value="normal" />
            <el-option label="紧急" value="urgent" />
            <el-option label="特急" value="critical" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAuditDialog">取消</el-button>
          <el-button type="primary" @click="submitAudit">提交审核</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核历史弹窗 -->
    <el-dialog 
      v-model="historyDialog.visible" 
      title="审核历史"
      width="70%"
      @close="closeHistoryDialog"
    >
      <el-timeline v-if="historyDialog.records.length">
        <el-timeline-item
          v-for="(record, index) in historyDialog.records"
          :key="index"
          :timestamp="record.auditTime"
          :type="getTimelineItemType(record.auditStatus)"
        >
          <el-card>
            <template #header>
              <div class="timeline-header">
                <span class="auditor-name">{{ record.auditor }}</span>
                <el-tag :type="getAuditStatusTagType(record.auditStatus)" size="small">
                  {{ getAuditStatusText(record.auditStatus) }}
                </el-tag>
              </div>
            </template>
            <div class="timeline-content">
              <p><strong>审核意见：</strong>{{ record.auditRemark || '无' }}</p>
              <p><strong>审核级别：</strong>{{ record.auditLevel || '无' }}</p>
              <p><strong>紧急程度：</strong>{{ record.urgency || '无' }}</p>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <div v-else class="no-history">
        暂无审核历史记录
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeHistoryDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { 
  Check, 
  Download, 
  Clock, 
  Close, 
  Document, 
  View, 
  Search, 
  Refresh 
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const auditFormRef = ref<FormInstance>()
const selectedVouchers = ref<any[]>([])

// 统计数据
const stats = reactive({
  pending: 15,
  approved: 42,
  rejected: 8,
  posted: 35
})

// 搜索表单
const searchForm = reactive({
  voucherNo: '',
  auditStatus: '',
  auditor: '',
  auditDateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 审核记录数据
const auditRecords = ref([
  {
    id: 1,
    voucherNo: 'V202401001',
    voucherType: 'sales',
    orderId: 'ORD202401001',
    totalAmount: 15000,
    auditStatus: 'pending',
    auditor: '',
    auditTime: '',
    auditRemark: ''
  },
  {
    id: 2,
    voucherNo: 'V202401002',
    voucherType: 'purchase',
    orderId: 'ORD202401002',
    totalAmount: 8500,
    auditStatus: 'approved',
    auditor: '张财务',
    auditTime: '2024-01-16 14:30:00',
    auditRemark: '审核通过，金额正确'
  },
  {
    id: 3,
    voucherNo: 'V202401003',
    voucherType: 'sales',
    orderId: 'ORD202401003',
    totalAmount: 22000,
    auditStatus: 'rejected',
    auditor: '李经理',
    auditTime: '2024-01-17 10:15:00',
    auditRemark: '金额计算有误，请重新核对'
  },
  {
    id: 4,
    voucherNo: 'V202401004',
    voucherType: 'refund',
    orderId: 'ORD202401004',
    totalAmount: 5000,
    auditStatus: 'posted',
    auditor: '王总监',
    auditTime: '2024-01-18 16:45:00',
    auditRemark: '审核通过，已过账'
  }
])

// 审核弹窗
const auditDialog = reactive({
  visible: false,
  title: '审核凭证',
  form: {
    voucherId: '',
    auditResult: 'approved',
    auditRemark: '',
    auditLevel: 'level1',
    urgency: 'normal'
  }
})

// 历史弹窗
const historyDialog = reactive({
  visible: false,
  records: []
})

// 表单验证规则
const auditRules = {
  auditResult: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  auditRemark: [{ required: true, message: '请输入审核意见', trigger: 'blur' }],
  auditLevel: [{ required: true, message: '请选择审核级别', trigger: 'change' }],
  urgency: [{ required: true, message: '请选择紧急程度', trigger: 'change' }]
}

// 方法
function getVoucherTypeTagType(type: string) {
  const types: Record<string, string> = {
    sales: 'success',
    purchase: 'warning',
    refund: 'danger'
  }
  return types[type] || 'info'
}

function getVoucherTypeText(type: string) {
  const texts: Record<string, string> = {
    sales: '销售凭证',
    purchase: '采购凭证',
    refund: '退款凭证'
  }
  return texts[type] || '未知类型'
}

function getAuditStatusTagType(status: string) {
  const types: Record<string, string> = {
    pending: 'info',
    approved: 'success',
    rejected: 'danger',
    posted: 'warning'
  }
  return types[status] || 'info'
}

function getAuditStatusText(status: string) {
  const texts: Record<string, string> = {
    pending: '待审核',
    approved: '已审核',
    rejected: '已驳回',
    posted: '已过账'
  }
  return texts[status] || '未知状态'
}

function getTimelineItemType(status: string) {
  const types: Record<string, string> = {
    pending: 'primary',
    approved: 'success',
    rejected: 'danger',
    posted: 'warning'
  }
  return types[status] || 'info'
}

function searchAuditRecords() {
  loading.value = true
  // 模拟搜索API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 1000)
}

function resetSearch() {
  searchForm.voucherNo = ''
  searchForm.auditStatus = ''
  searchForm.auditor = ''
  searchForm.auditDateRange = []
  searchAuditRecords()
}

function handleSelectionChange(selection: any[]) {
  selectedVouchers.value = selection
}

function batchAudit() {
  if (selectedVouchers.value.length === 0) {
    ElMessage.warning('请选择要审核的凭证')
    return
  }
  
  ElMessageBox.confirm(
    `确定要批量审核选中的 ${selectedVouchers.value.length} 个凭证吗？`,
    '批量审核',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟批量审核
    selectedVouchers.value.forEach(voucher => {
      voucher.auditStatus = 'approved'
      voucher.auditor = '系统批量审核'
      voucher.auditTime = new Date().toLocaleString()
      voucher.auditRemark = '批量审核通过'
    })
    
    ElMessage.success('批量审核完成')
    selectedVouchers.value = []
  }).catch(() => {})
}

function viewVoucherDetail(voucher: any) {
  ElMessage.info(`查看凭证详情：${voucher.voucherNo}`)
}

function approveVoucher(voucher: any) {
  openAuditDialog(voucher, '审核凭证')
}

function rejectVoucher(voucher: any) {
  openAuditDialog(voucher, '驳回凭证')
}

function postVoucher(voucher: any) {
  ElMessageBox.confirm(
    `确定要将凭证 ${voucher.voucherNo} 过账吗？`,
    '过账确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    voucher.auditStatus = 'posted'
    voucher.auditTime = new Date().toLocaleString()
    ElMessage.success('过账成功')
  }).catch(() => {})
}

function viewAuditHistory(voucher: any) {
  // 模拟审核历史数据
  historyDialog.records = [
    {
      auditor: '张财务',
      auditStatus: 'approved',
      auditTime: '2024-01-16 14:30:00',
      auditRemark: '一级审核通过',
      auditLevel: 'level1',
      urgency: 'normal'
    },
    {
      auditor: '李经理',
      auditStatus: 'approved',
      auditTime: '2024-01-17 09:15:00',
      auditRemark: '二级审核通过',
      auditLevel: 'level2',
      urgency: 'normal'
    }
  ]
  historyDialog.visible = true
}

function openAuditDialog(voucher: any, title: string) {
  auditDialog.title = title
  auditDialog.form.voucherId = voucher.id
  auditDialog.form.auditResult = title.includes('驳回') ? 'rejected' : 'approved'
  auditDialog.form.auditRemark = ''
  auditDialog.visible = true
}

function closeAuditDialog() {
  auditDialog.visible = false
  auditFormRef.value?.resetFields()
}

function closeHistoryDialog() {
  historyDialog.visible = false
  historyDialog.records = []
}

function submitAudit() {
  auditFormRef.value?.validate((valid) => {
    if (valid) {
      const voucher = auditRecords.value.find(v => v.id === auditDialog.form.voucherId)
      if (voucher) {
        voucher.auditStatus = auditDialog.form.auditResult
        voucher.auditor = '当前用户' // 实际应该从用户状态获取
        voucher.auditTime = new Date().toLocaleString()
        voucher.auditRemark = auditDialog.form.auditRemark
        
        ElMessage.success('审核提交成功')
        closeAuditDialog()
      }
    }
  })
}

function exportAuditLog() {
  ElMessage.success('导出功能开发中...')
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  searchAuditRecords()
}

function handleCurrentChange(val: number) {
  pagination.currentPage = val
  searchAuditRecords()
}

// 页面加载
onMounted(() => {
  pagination.total = auditRecords.value.length
  searchAuditRecords()
})
</script>

<style scoped>
.finance-audit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.audit-stats {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-card.pending {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stat-card.approved {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-card.rejected {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-card.posted {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stat-icon {
  font-size: 48px;
  margin-right: 16px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.auditor-name {
  font-weight: 500;
  color: #303133;
}

.timeline-content p {
  margin: 8px 0;
  color: #606266;
}

.no-history {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
